package com.zxl.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.zxl.config.AlipayConfig;
import com.zxl.feign.OrderFeign;
import com.zxl.vo.Order;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Map;

/**
 * @packageName com.zxl.controller
 * @ClassName
 * @Author zxl
 * @Description //TODO
 * @date
 **/
@Controller
@RequestMapping("/ali")
@Slf4j
public class AlipayController {

    @Autowired
    private OrderFeign orderFeign;

    @RequestMapping("/pay")
    public void payController(String oid, HttpServletResponse response) throws IOException {

        Order order = orderFeign.getByOid(oid);

        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl,
                AlipayConfig.app_id,
                AlipayConfig.merchant_private_key,
                "json",
                AlipayConfig.charset,
                AlipayConfig.alipay_public_key,
                AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);


        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = order.getId();
        //付款金额，必填
        Double total_amount = order.getTotalPrice();
        //订单名称，必填
        String subject = order.getUname() + "的订单";
        //商品描述，可空
        String body = order.getUname() + "的订单,总价为:" + order.getTotalPrice();


        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");


        //请求
        String form = "";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        response.setContentType("text/html;charset=" + AlipayConfig.charset);
        response.getWriter().write(form);//直接将完整的表单html输出到页面
        response.getWriter().flush();
        response.getWriter().close();
    }

    @PostMapping("/updateOrder")
    public void updateOrder(@RequestBody Map<String,String> map, HttpServletResponse response) {

        log.debug("map中的参数为：", map);
        boolean b = false;
        try {

            //验签，保证安全性,是支付宝发的则true
            b = AlipaySignature.rsaCheckV1(map,
                    AlipayConfig.alipay_public_key,
                    AlipayConfig.charset,
                    AlipayConfig.sign_type
            );
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if (b){
            //判断订单状态trade_status是否支付成功（TRADE_SUCCESS）
            if ("TRADE_SUCCESS".equals(map.get("trade_status"))) {
                //对订单的状态信息进行修改
                String oid = map.get("out_trade_no");
                orderFeign.updateOrder(oid,2);
            }else {
                log.debug("支付不成功");
            }

        }else {
            //不是支付宝发的不能够去更改订单状态
            log.debug("验签不通过");
        }

    }

}
